package com.ffapp.helper.query;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.helper.R;
import com.ffapp.helper.bean.ParamListData;
import com.ffapp.helper.eventbus.PopHandleMessage;
import com.ffapp.helper.home.HomeBaseActivity;
import com.ffapp.helper.util.SubstringUtil;
import com.ffapp.helper.view.PopHandle;
import com.suke.widget.SwitchButton;

import java.util.ArrayList;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.MySharedPreferences;

public class QueryIndexActivity extends HomeBaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> queryList;
    private boolean isOnPause = false;
    private boolean isContinuRefresh = false;
    private boolean isPicture = false;
    MySharedPreferences mSp;
    @BindView(R.id.btn_update)
     Button saveBtn ;

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.activity_query);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);


        setTitleLeftText("查询信息", Color.WHITE, null);
        mSp = new MySharedPreferences(mContext);

        switch (mSp.getDevType()) {
            case "F-CD100":
                saveBtn.setVisibility(View.VISIBLE);
                setTitleRightButton(R.mipmap.refresh, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isContinuRefresh = false;
                        isOnPause = true;
                        isPicture = false;
                        showProgress();
                        sendAtSearchOrTakePicture();
                    }
                });
                break;
            case "F9164-M":
                setTitleRightButton2(R.mipmap.camera, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isContinuRefresh = false;
                        isOnPause = true;
                        isPicture = true;
                        showProgress();
                        sendAtSearchOrTakePicture();
                    }
                });
                break;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        queryList = new ArrayList<>();
    }

    private void sendAtSearchOrTakePicture() {
        BleUtils.sendAtSearchOrTakePicture(mContext,isPicture,new BleUtils.BleUtilCallBack() {
            @Override
            public void onWriteFailure(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onSuccess(String message) {
                dismissProgress();
                showToast(message);
            }

            @Override
            public void onError(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onResult(StringBuffer message) {
                setList(message.toString());
                dismissProgress();
                Log.d("isOnPause===",""+isOnPause);
                if(!isOnPause){
                    handler.postDelayed(runnable, 5000);
                }
            }

            @Override
            public void onByte(byte[] bytes) {
                dismissProgress();
                BleLog.d("bytes ===="+Arrays.toString(bytes));
                BleLog.d("bytes ====ToHexString ===="+HexUtil.bytesToHexString(bytes));
                BleLog.d("bytes ====ToHexString ====hexStringToString==="+HexUtil.hexStringToString(HexUtil.bytesToHexString(bytes)));

//                    将byte[]类型转换成Bitmap类型
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                PopHandle popHandle = new PopHandle(mContext, "bitmap", bitmap);
                popHandle.show();
            }
        });
    }

    public void setList(String sMsgObjString) {
        if (isFinishing()) {
            return;
        }
        queryList.clear();
        if (!TextUtils.isEmpty(sMsgObjString)) {

            //信号强度
            String sysCSQ = SubstringUtil.subString(sMsgObjString, "SysCSQ:");
            queryList.add(new ParamListData("信号强度", 2, "" + sysCSQ, "", ""));

            //GPRS状态
            String gprsSt = SubstringUtil.subString(sMsgObjString, "GprsSt:");
            switch (gprsSt) {
                case "0":
                    gprsSt = "网络开始状态";
                    break;
                case "1":
                    gprsSt = "网络初始化状态";
                    break;
                case "2":
                    gprsSt = "网络待机状态（4G模块只使用短信时使用）";
                    break;
                case "3":
                    gprsSt = "网络连接状态（LORA及北斗使用）";
                    break;
                case "4":
                    gprsSt = "网络连接成功状态（LORA及北斗使用）";
                    break;
                case "5":
                    gprsSt = "网络拨号状态";
                    break;
                case "6":
                    gprsSt = "网络拨号成功状态";
                    break;
                case "7":
                    gprsSt = "网络关闭状态";
                    break;
                case "8":
                    gprsSt = "网络停止状态";
                    break;
                case "9":
                    gprsSt = "网络未处理状态";
                    break;
            }
            queryList.add(new ParamListData("信号强度", 2, "" + gprsSt, "", ""));

            //电池电压
            String batVolt = SubstringUtil.subString(sMsgObjString, "BatVolt:");
            queryList.add(new ParamListData("电池电压", 2, "" + batVolt, "", "伏"));


            switch (mSp.getDevType()) {
                case "F-CD100":
                    //设备温度
                    String devTemp = SubstringUtil.subString(sMsgObjString, "DevTemp:");
                    queryList.add(new ParamListData("设备温度", 2, "" + devTemp, "", "度"));

                    //水位
                    String curWaterLevel = SubstringUtil.subString(sMsgObjString, "CurWaterLevel:");
                    queryList.add(new ParamListData("水位", 2, "" + curWaterLevel, "", "米"));

                    //瞬时流量
                    String curFlow = SubstringUtil.subString(sMsgObjString, "CurFlow:");
                    queryList.add(new ParamListData("瞬时流量", 2, "" + curFlow, "", "立方米每秒"));

                    //Socket1 Socket2 Socket3 Socket4状态
                    String centerSt = SubstringUtil.subString(sMsgObjString, "CenterSt:");
                    String[] centerSts = centerSt.split(",");
                    for (int i = 0; i < centerSts.length; i++) {
                        String value = "";
                        switch (centerSts[i]) {
                            case "0":
                                value = "无";
                                break;
                            case "1":
                                value = "开始状态";
                                break;
                            case "2":
                                value = "初始状态";
                                break;
                            case "3":
                                value = "解析域名等待";
                                break;
                            case "4":
                                value = "解析域名中";
                                break;
                            case "5":
                                value = "创建实例";
                                break;
                            case "6":
                                value = "连接中";
                                break;
                            case "7":
                                value = "连接成功后等待";
                                break;
                            case "8":
                                value = "连接成功";
                                break;
                            case "9":
                                value = "NB连接成功";
                                break;
                            case "10":
                                value = "连接关闭";
                                break;
                            case "11":
                                value = "连接停止";
                                break;
                        }
                        queryList.add(new ParamListData("Socket" + (i + 1) + "状态", 2, "" + value, "", ""));
                    }

                    //定时采集间隔
                    String sampleInt = SubstringUtil.subString(sMsgObjString, "SampleInt:");
                    queryList.add(new ParamListData("定时采集间隔", 2, "" + sampleInt, "", "分"));

                    //定时上报间隔
                    String reportInt = SubstringUtil.subString(sMsgObjString, "Report Int:");
                    queryList.add(new ParamListData("定时上报间隔", 2, "" + reportInt, "", "分"));
                    break;

                case "F9164-M":
                case "F9164-L":
                case "F9164-LD":

                    //第一通道采集数值，数值有可能是小数
                    String passWayOne = SubstringUtil.subString(sMsgObjString, "CH1 Dat:");
                    String[] passWayOnes = passWayOne.split(",");
                    if (passWayOnes.length == 1) {
                        queryList.add(new ParamListData("第一通道", 2, "" + passWayOnes[0], "", ""));
                    } else if (passWayOnes.length == 2) {
                        queryList.add(new ParamListData("第一通道", 2, "" + passWayOnes[0], "", "" + passWayOnes[1]));
                    }


                    //第二通道采集数值，数值有可能是小数
                    String passWayTwo = SubstringUtil.subString(sMsgObjString, "CH2 Dat:");
                    String[] passWayTwos = passWayTwo.split(",");
                    if (passWayTwos.length == 1) {
                        queryList.add(new ParamListData("第二通道", 2, "" + passWayTwos[0], "", ""));
                    } else if (passWayTwos.length == 2) {
                        queryList.add(new ParamListData("第二通道", 2, "" + passWayTwos[0], "", "" + passWayTwos[1]));
                    }


                    //第三通道采集数值，数值有可能是小数
                    String passWayThree = SubstringUtil.subString(sMsgObjString, "CH3 Dat:");
                    String[] passWayThrees = passWayThree.split(",");
                    if (passWayThrees.length == 1) {
                        queryList.add(new ParamListData("第三通道", 2, "" + passWayThrees[0], "", ""));
                    } else if (passWayTwos.length == 2) {
                        queryList.add(new ParamListData("第三通道", 2, "" + passWayThrees[0], "", "" + passWayThrees[1]));
                    }


                    //第四通道采集数值，数值有可能是小数
                    String passWayFour = SubstringUtil.subString(sMsgObjString, "CH4 Dat:");
                    String[] passWayFours = passWayFour.split(",");
                    if (passWayFours.length == 1) {
                        queryList.add(new ParamListData("第四通道", 2, "" + passWayFours[0], "", ""));
                    } else if (passWayTwos.length == 2) {
                        queryList.add(new ParamListData("第四通道", 2, "" + passWayFours[0], "", "" + passWayFours[1]));
                    }


                    //第五通道采集数值，数值有可能是小数
                    String passWayFive = SubstringUtil.subString(sMsgObjString, "CH5 Dat:");
                    String[] passWayFives = passWayFive.split(",");
                    if (passWayFives.length == 1) {
                        queryList.add(new ParamListData("第五通道", 2, "" + passWayFives[0], "", ""));
                    } else if (passWayTwos.length == 2) {
                        queryList.add(new ParamListData("第五通道", 2, "" + passWayFives[0], "", "" + passWayFives[1]));
                    }

                    break;
            }

        }
        adapter.notifyDataSetChanged();
//        recyclerView.setAdapter(adapter);
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_pass_way_base_item, viewGroup, false);
            return new MyAdapter.ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return queryList == null ? 0 : queryList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                ParamListData queryListData = queryList.get(position);
                tvName.setText(queryListData.getName());
                editText.setText("" + queryListData.getValue());
                tvUnit.setVisibility(View.VISIBLE);
                tvUnit.setText(queryListData.getUnit());
                imgSpanner.setVisibility(View.GONE);
                switchBtn.setVisibility(View.GONE);
                editText.setEnabled(false);//可编辑
                list_item.setBackgroundResource(R.color.white);
            }
        }
    }


    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {//推送runnable，定期2s执行一次
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Log.d("QueryIndexActivity", "runnable");
            if (!isOnPause) {
                sendAtSearchOrTakePicture();
            }
        }
    };


    @OnClick(R.id.btn_update)
    public void update() {
        if (isContinuRefresh) {
            showToast("已持续更新，请勿重复点击");
            return;
        }
        handler.post(runnable);//定期执行
        isOnPause = false;
        isContinuRefresh = true;
        isPicture = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private boolean isFront = false;

    @Override
    protected void onResume() {
        super.onResume();
        isFront = true;
    }

    @Override
    protected void onPause() {
        BleUtils.stopNotify();
        isFront = false;
        isOnPause = true;
        isContinuRefresh = false;
        isPicture = false;
        super.onPause();
    }

    @Override
    public void onMessageEvent(PopHandleMessage event) {
        super.onMessageEvent(event);
        BleLog.d("onDisConnected =PopHandleMessage==" + event.message);
        if (isFront) {
            BleUtils.reConnect(mContext, new BleUtils.BleUtilLoginCallBack() {
                @Override
                public void isLogin(boolean isSuccess, String message) {
                    if (isSuccess) {
                        showToast("" + message);
                        dismissProgress();
                    }
                }
            });
        }
    }
}
